package com.qixiucoding;//继承RecursiveTask类，自己实现Fork/Join，其实就是写算法，如何拆分子任务

import java.util.concurrent.RecursiveTask;
/**
 * @author: wangwren
 * @date: 2019/4/6
 * @descripton: 要计算0至一亿的和，自己先使用fork/join实现一下
 *                   RecursiveTask是带有返回值的，RecursiveAction不带有返回值
 *                  Recursive的意思是“递归”
 * @version: 1.0
 */
public class ForkJoinCalcuate extends RecursiveTask<Long> {
    private long start;
    private long end;

    //临界值，设为一万，即小任务中包含一万个数
    private static final long THRESHOLD = 10000L;
    public ForkJoinCalcuate(long start,long end){
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long length = end - start;
        if (length <= THRESHOLD){
            long sum = 0;
            //循环相加
            for (long i = start;i <= end;i++){
                sum += i;
            }
            return sum;
        }else{
            //对任务进行拆分
            long middle = (start + end) / 2;
            ForkJoinCalcuate left = new ForkJoinCalcuate(start,middle);
            //拆分，并将该子任务压入线程队列
            //fork是ForkJoinTask提供的方法
            left.fork();
            ForkJoinCalcuate right = new ForkJoinCalcuate(middle + 1,end);
            right.fork();
            //合并
            return left.join() + right.join();
        }
    }
}
